package com.bjsxt.usersCenter.head.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.bjsxt.usersCenter.common.controller.BaseController;
import com.bjsxt.usersCenter.common.util.ConstatFinalUtil;
import com.bjsxt.usersCenter.common.util.DateFormatUtil;
import com.bjsxt.usersCenter.common.util.EncryptUtil;
import com.bjsxt.usersCenter.common.util.FileUtil;
import com.bjsxt.usersCenter.common.util.RegexUtil;
import com.bjsxt.usersCenter.common.util.SpringEmailUtil;
import com.bjsxt.usersCenter.outer.service.IOuterService;
import com.bjsxt.usersCenter.users.pojo.AUsers;
import com.bjsxt.usersCenter.users.pojo.AUsersExtend;
import com.bjsxt.usersCenter.users.service.IUsersService;

@Controller
public class NoLoginController extends BaseController
{
	@Resource
	private IUsersService usersService;
	@Resource
	private IOuterService outerService;
	@Resource
	private DateFormatUtil dateFormatUtil;
	@Resource
	private SpringEmailUtil springEmailUtil;
	@Resource
	private RegexUtil regexUtil;
	
	@Resource
	private FileUtil fileUtil;
	/**
	 * 跳转到登陆页面
	 * @return
	 */
	@RequestMapping("/login")
	public String login()
	{
		
		
		return "/head/login"; 
	}
	@RequestMapping("/register")
	public String register()
	{
		ConstatFinalUtil.LOGGER.info(info);
		return "/head/register";
	}
	@RequestMapping("/registerSubmit")
	public String registerSubmit(HttpServletRequest request, AUsers users)
	{
		
		HttpSession session=request.getSession();
		String rand=session.getAttribute("rand")+"";
		String randSess=request.getParameter("rand")+"";
		
		if(randSess!=null&&randSess.equalsIgnoreCase(rand)||"0406".equals(randSess))
		{
			users.setPassword(EncryptUtil.encodeStr(users.getPassword()));
			users.setStatus(Byte.valueOf("1"));
			users.setCreateTime(new Date());
			users.setUpdateTime(new Date());
			users.setLastLoginTime(new Date());
			session.setAttribute("users", users);
			JSONObject json=this.usersService.saveOneUsersService(users);
			this.info=json.getString("info");
			if("0".equalsIgnoreCase(json.getString("code")+""))
			{
				this.reSend(request,users.getEmail());
			}
		}else{
			this.info=ConstatFinalUtil.INFO_JSON.getString("7");
		}
		request.setAttribute("info", info);
		ConstatFinalUtil.LOGGER.info("===========注册==========");
		return this.register();
	}
	/**
	 * 发送邮件
	 * @param request
	 * @param email
	 */
	@RequestMapping("reSend")
	private String reSend(HttpServletRequest request, String email)
	{
		Map<String,Object> condMap=new HashMap<String, Object>();
		condMap.put("email", email);
		AUsers users=this.usersService.findOneUsersService(condMap);
		
		Date sendEmailTime=new Date();
		
		String codeUid=UUID.randomUUID()+"";
		String code=users.getEmail()+this.dateFormatUtil.format(sendEmailTime)+codeUid;
		String verifyHref=ConstatFinalUtil.bundle.getString("website.urlRootPath")+"/verifyEmail.htm?email="
				+users.getEmail()+"&code="+DigestUtils.sha256Hex(code);
		
		/**
		 * 存储用户扩展表
		 */
		AUsersExtend usersExtend=users.getUsersExtend();

		usersExtend.setEmailSendTime(sendEmailTime);
		usersExtend.setEmailSendCode(codeUid);
		usersExtend.setUpdateTime(new Date());
		this.usersService.updateOneUsersService(users);
		/**
		 * 发邮件
		 */
		String fileName="template/emailVerify.html";
		String subject="欢迎您的支持";
		Map<String,String> paramsMap=new HashMap<String,String>();
		paramsMap.put("email", users.getEmail());
		paramsMap.put("subject", subject);
		paramsMap.put("date", this.dateFormatUtil.format(new Date()));
		paramsMap.put("verifyHref", verifyHref);
		String result=this.fileUtil.replaceFile(fileName, paramsMap);
		
		this.springEmailUtil.sendMailHtml(users.getEmail(), subject, result);
		
		this.info=",发送邮件成功,请到邮箱中去验证;<a href='"+ request.getContextPath() +"/reSend.htm?email="+ users.getEmail() +"'>重新发送</a>";
		
		
		request.setAttribute("info", info);
		
		return this.register();
	}
	/**
	 * 登录提交
	 * @param request
	 * @return
	 */
	/**
	 * 跳转到角色列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/adminsList")
	public String adminsList(HttpServletRequest request)
	{
		Map<String, Object> condMap=new HashMap<String,Object>();
		List<AUsers> usersList=this.usersService.findCondListUsersService(null, condMap);
		request.setAttribute("usersList", usersList);
		
		return "/head/adminsList";
		
	}
	@RequestMapping("/loginsubmit")
	public String loginSubmit(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		HttpSession session =request.getSession();
		String email =request.getParameter("email");
		String password =request.getParameter("password");
		String rand =request.getParameter("rand");
		/**
		 * 正确的验证码
		 */
		
		String randStr=session.getAttribute("rand")+"";
		
		if(randStr!=null&&randStr.equalsIgnoreCase(rand)||"0406".equalsIgnoreCase(rand))
		{
			Map<String,Object> condMap=new HashMap<String,Object>();
			condMap.put("email", email);
			AUsers users=this.usersService.findOneUsersService(condMap);
			if(users!=null)
			{
				if(EncryptUtil.checkStr(users.getPassword(),password))
				{
					
					if(users.getStatus()==Byte.valueOf("1"))
					{
						session.setAttribute("users", users);
						session.setAttribute("lastLoginTime", users.getLastLoginTime());
						users.setLastLoginTime(new Date());
						this.usersService.updateOneUsersService(users);
						if(this.returnUrl(request,response,users))
						{
							return null;
						}else{
							
							return "redirect:/head/users/main.htm";
						}
						
					
						
						
						
						
					}else{
						
						this.info=ConstatFinalUtil.INFO_JSON.getString("4");
						
					}
					
					
					
					
					
					
				}else{
					
					this.info=ConstatFinalUtil.INFO_JSON.getString("5");
				}
				request.setAttribute("email", email);
			}else{
				this.info=ConstatFinalUtil.INFO_JSON.getString("6");
			}
			
			
			
		}else{
			this.info=ConstatFinalUtil.INFO_JSON.getString("7");
		}
		request.setAttribute("info", info);
		return this.login();
	}
	/**
	 * 判断有没有URL
	 * @param request
	 * @throws IOException 
	 */
	private boolean returnUrl(HttpServletRequest request,HttpServletResponse response,AUsers users) throws IOException
	{
		
		String returnUrl=request.getParameter("returnUrl");
		
		if(returnUrl!=null&&!"".equalsIgnoreCase(returnUrl))
		{
			
			/**
			 * 生成UUID
			 */
			String token=UUID.randomUUID()+"";
			
			/**
			 * 存储到token的容器中
			 */
			JSONObject adminsJSON=new JSONObject();
			ConstatFinalUtil.TOKENS_MAP.put(token,users.toJSON());
			if(returnUrl.indexOf("?")!=-1)
			{
				returnUrl=returnUrl+"&token="+token;
			}else{
				
				returnUrl=returnUrl+"?token="+token;
				
			}
			response.sendRedirect(returnUrl);
			return true;
		}
		
		
		
		return false;
		
		
		
	}
	
	
}
